package com.share.tool.mock.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.share.common.common.Page;
import com.share.tool.mock.mapper.DataLogMapper;
import com.share.tool.mock.model.db.DataLog;
import com.share.tool.mock.model.vo.LogPageListReq;
import com.share.tool.mock.service.DataLogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class DataLogServiceImpl extends ServiceImpl<DataLogMapper, DataLog> implements DataLogService {
    @Resource
    private DataLogMapper dataLogMapper;

    @Override
    public int insertLog(DataLog dataLog) {
        if (dataLog == null) {
            return 0;
        }

        if (dataLog.getStartTime() != null && dataLog.getEndTime() != null) {
            dataLog.setCosts(dataLog.getEndTime().getTime() - dataLog.getStartTime().getTime());
        }
        return dataLogMapper.insert(dataLog);
    }

    @Override
    public Page pageList(LogPageListReq req) {
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        LambdaQueryWrapper<DataLog> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(req.getCode())) {
            queryWrapper.like(DataLog::getCode, req.getCode());
        }
        if (StringUtils.isNotBlank(req.getRequest())) {
            queryWrapper.like(DataLog::getRequest, req.getRequest());
        }
        if (StringUtils.isNotBlank(req.getResponse())) {
            queryWrapper.like(DataLog::getResponse, req.getResponse());
        }
        queryWrapper.orderByDesc(DataLog::getId);
        List<DataLog> list = dataLogMapper.selectList(queryWrapper);
        return new Page<>(list, new PageInfo<>(list).getTotal(), req);
    }
}
